<template>
  <el-cascader
    v-model="selectedValue"
    :options="options"
    :props="cascaderProps"
    :disabled="disabled"
    :placeholder="placeholder"
    clearable
    filterable
    @change="handleChange"
  />
</template>

<script setup>
import { getRegionTree } from '@/api/system/region'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: '35'
  },
  regionName: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择'
  }
})

const emit = defineEmits(['update:modelValue', 'update:regionName'])

const selectedValue = computed({
  get: () => props.modelValue ? [props.modelValue] : [],
  set: val => {
    emit('update:modelValue', val[val.length - 1] || '')
  }
})

const options = ref([])

// 重命名为 cascaderProps 避免命名冲突
const cascaderProps = {
  lazy: true,
  lazyLoad: (node, resolve) => {
    const { level, value } = node
    getRegionTree({
      parentCode: !value || value === 0 ? '35' : value
    }).then(res => {
      if (res.code === 200) {
        const nodes = res.data.map(item => ({
          value: item.key,
          label: item.title,
          leaf: level >= 1
        }))
        resolve(nodes)
      }
    })
  },
  value: 'value',
  label: 'label'
}

// 选择改变
function handleChange(value, selectedOptions) {
  if (selectedOptions.length) {
    const names = selectedOptions.map(option => option.label)
    emit('update:regionName', names.join('/'))
  } else {
    emit('update:regionName', '')
  }
}

// 初始化已选值
onMounted(() => {
  if (props.modelValue) {
    // 根据code获取完整路径
    getRegionTree({ parentCode: props.modelValue }).then(res => {
      if (res.code === 200 && res.data.length) {
        selectedValue.value = [props.modelValue]
      }
    })
  }
})
</script> 